<template>
  <div class="dashboard-container">
    <div class="app-container">
      <div class="edit-form">
        <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="220px">
          <!-- 姓名-->
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="username">
                <el-input v-model="userInfo.username" size="mini" class="inputW" />
              </el-form-item>
            </el-col>

          </el-row>
          <!-- 工号  -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="工号" prop="workNumber">
                <el-input v-model="userInfo.workNumber" disabled size="mini" class="inputW" />
              </el-form-item>
            </el-col>
          </el-row>
          <!--手机   -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机" prop="mobile">
                <el-input
                  v-model="userInfo.mobile"
                  :disabled="!!userInfo.id"
                  size="mini"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门" prop="departmentId">
                <!-- 放置及联部门组件 -->
                <el-cascader
                  v-model="userInfo.departmentId"
                  class="inputW"
                  size="mini"
                  :options="deptList"
                  :props="{label: 'name', value: 'id'}"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="聘用形式" prop="formOfEmployment">
                <el-select v-model="userInfo.formOfEmployment" size="mini" class="inputW">
                  <el-option label="正式" :value="1" />
                  <el-option label="非正式" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入职时间" prop="timeOfEntry">
                <el-date-picker
                  v-model="userInfo.timeOfEntry"
                  size="mini"
                  type="date"
                  value-format="yyyy-MM-dd"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="转正时间" prop="correctionTime">
                <el-date-picker
                  v-model="userInfo.correctionTime"
                  size="mini"
                  type="date"
                  class="inputW"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 员工照片 --> {{ lastDeptId }} ----
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工头像">
                <!-- 放置上传图片 -->
                <UploadImage v-model="userInfo.staffPhoto" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 保存个人信息 -->
          <el-row type="flex">
            <el-col :span="12" style="margin-left:220px">
              <el-button size="mini" type="primary" @click="saveData">保存更新</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </div>
  </div>
</template>

<script>
import { getDeptList } from '@/api/department'
import { addEmployee, getEmployeeDetail, UpdateEmployeeDetail } from '@/api/employee'
import { transformToTreedata } from '@/utils'
import UploadImage from './components/upload-image.vue'
export default {
  components: {
    UploadImage
  },
  data() {
    return {
      userInfo: {
        username: '', // 用户名
        mobile: '', // 手机号
        workNumber: '', // 工号
        formOfEmployment: null, // 聘用形式
        departmentId: null, // 部门id
        timeOfEntry: '', // 入职时间
        correctionTime: '', // 转正时间
        staffPhoto: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          {
            pattern: /^(?:[\u4e00-\u9fa5·]{2,4})$/, message: '请输入正确的的姓名'
          }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
          //   pattern 正则表达式
          pattern: /^1[3-9]\d{9}$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'change' }],
        departmentId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }, {
          validator: (rule, value, callback) => {
            if (this.userInfo.timeOfEntry) {
              if (new Date(this.userInfo.timeOfEntry) > new Date(value)) {
                callback(new Error('转正时间不能小于入职时间'))
                return
              }
            }
            callback()
          }
        }]
      },
      deptList: [], // 部门列表
      lastDeptId: null // 最后的部门id
    }
  },
  watch: {
    // 侦听departmentId的变化 拿到最后一项部门的id
    'userInfo.departmentId'(newVal) {
      console.log(newVal)
      if (typeof newVal === 'number') {
        this.lastDeptId = newVal
      } else {
        this.lastDeptId = newVal[newVal.length - 1]
      }
    }
  },
  created() {
    this.getDeptList()
    this.$route.params.id && this.getEmployeeDetail()
  },
  methods: {
    saveData() {
      // 1. 预校验
      this.$refs.userForm.validate(async boo => {
        if (!boo) return
        // 2. 发送请求
        // console.log({ ...this.userInfo, departmentId: this.userInfo.departmentId[this.userInfo.departmentId.length - 1] })
        // console.log({ ...this.userInfo, departmentId: this.lastDeptId })
        // if (this.userInfo.id) {
        if (this.$route.params.id) {
          // console.log({ ...this.userInfo, departmentId: this.lastDeptId })
          await UpdateEmployeeDetail({ ...this.userInfo, departmentId: this.lastDeptId })
          this.$message.success('修改成功')
        } else {
          await addEmployee({ ...this.userInfo, departmentId: this.lastDeptId })
          // 3. 提示
          this.$message.success('新增成功')
        }

        // 4. 跳转到员工页面
        this.$router.back()
      })
    },
    // 部门列表
    async getDeptList() {
      const res = await getDeptList()
      this.deptList = transformToTreedata(res.data, 0)
    },
    // 级联选择器选择修改触发的事件
    handleChange(vals) {
      console.log(this.userInfo.departmentId)
      // this.userInfo.departmentId = vals[vals.length - 1]
    },
    // 获取员工详情
    async getEmployeeDetail() {
      const res = await getEmployeeDetail(this.$route.params.id)
      this.userInfo = res.data // 将个人信息交给userInfo, departmentId 是数字id
      // console.log(res.data.departmentId)
      this.lastDeptId = this.userInfo.departmentId // 又存储一份部门id  赋值会导致侦听器听到
    }
  }
}
</script>

<style scoped lang="scss">
    .edit-form {
      background: #fff;
      padding: 20px;
      .inputW {
        width: 380px
      }
    }

</style>
